#include "StdAfx.h"
#include "UserInfo.h"
#include "FreeMSDlg.h"
#include "P2PSocketWatcher.h"
#include "StdDef.h"
CP2PSocketWatcher::CP2PSocketWatcher(void)
{
	m_asynP2PSendSocket.SetSockWacher(this);
	m_asynP2PRecvSocket.SetSockWacher(this);
}

CP2PSocketWatcher::~CP2PSocketWatcher(void)
{
	UnInitalize();
}
BOOL CP2PSocketWatcher::Initalize()
{
	BOOL bInit = FALSE;
	do 
	{
		if (!m_asynP2PSendSocket.Create(P2P_SEND_PORT,SOCK_DGRAM))
		{
			break;
		}
		if (!m_asynP2PRecvSocket.Create(P2P_RECV_PORT,SOCK_DGRAM))
		{
			break;
		}
		bInit = TRUE;
	} while (FALSE);

	return bInit;
}
BOOL CP2PSocketWatcher::UnInitalize()
{
	m_asynP2PRecvSocket.Close();
	m_asynP2PSendSocket.Close();
	return TRUE;
}
void CP2PSocketWatcher::OnReceive(int nErrorCode)
{
	//	CAsyncSocketEx::OnReceive(nErrorCode);
	//AfxMessageBox(L"OnReceive");
	if (nErrorCode==0)
	{
		char pBuffer[1024*8] = {0};
		SOCKADDR_IN sockAddr = {0};
		//	m_sockAddr.sin_family=AF_INET;
		//	m_sockAddr.sin_port = htons(BROADCAST_RECV_PORT);
		//	m_sockAddr.sin_addr.s_addr=htonl(INADDR_BROADCAST);
		INT nSockLen = sizeof(sockAddr);
		INT nRecvLen = m_asynP2PRecvSocket.RecvFrom(pBuffer,1024*8,0,(sockaddr*)&sockAddr,&nSockLen);
		if (nRecvLen == SOCKET_ERROR)
		{
#ifdef _DEBUG
			DWORD er=m_asynP2PRecvSocket.GetLastError();
#endif
			return;
		}
		CMsData recvData(pBuffer,nRecvLen);
		switch (recvData.GetMsgType())
		{
		case MS_REPLY_USER_INFO:
			{
				CUserInfo * pUserInfo = (CUserInfo *)recvData.GetMsgValue();
				CFreeMSDlg * pMsDlg = (CFreeMSDlg * )AfxGetApp()->GetMainWnd();
				if (MSUTIL::IsNotNull(pMsDlg))
				{
					pMsDlg->UpdateUserInfo(pUserInfo);
				}
			}break;
		default:
			break;
		}
	}
}
INT CP2PSocketWatcher::SendTo(const char * pBuffer,INT nBufferLen,const char * pszIP)
{
	SOCKADDR_IN sendToAddr = { 0 };
	sendToAddr.sin_family = AF_INET;
	sendToAddr.sin_addr.s_addr = inet_addr(pszIP);
	sendToAddr.sin_port = htons(P2P_RECV_PORT);
	INT nSendLen = m_asynP2PSendSocket.SendTo(pBuffer,nBufferLen,0,(sockaddr*)&sendToAddr);
	return nSendLen;
}